#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from qtpy import QtCore, QtGui
import os


class TreeItem(object):
    def __init__(self, data={}, parent=None):
        self.parent_item = parent
        # self.itemData = path
        self.childNames = []
        self.childItems = []
        self.__data = data
        self.name = data.get('code', '')

    def child(self, row):
        name = self.childNames[row]
        for item in self.childItems:
            if item.data() == name:
                return item
    
    def listChildren(self):
        return self.childItems
        
    def addChild(self, item):
        self.childItems.append(item)
        self.childNames.append(item.data())
        self.childNames.sort()
    
    def childCount(self):
        # return 1
        return len(self.childItems)
    
    def columnCount(self):
        return 1
        # return len(self.itemData)
        
    def row(self):
        if self.parent_item:
            return self.parent_item.childNames.index(self.data())
        return 0
    def rowCount(self):
        return len(self.childItems)

    def data(self, column=1):
        # return os.path.basename(self.path)
        return self.name

    def parent(self):
        return self.parent_item
        
class TreeModel(QtCore.QAbstractItemModel):
    def __init__(self, data, parent=None):
        super(TreeModel, self).__init__(parent)


        self.rootData = data
        self.items = []
        self.rootItem = TreeItem()
        self.items.append(self.rootItem)
        if self.rootData:
            self.updata_data_scan()

        
    # def setData(self, index, value, role=QtCore.Qt.EditRole):

    #     item = self.itemFromIndex(index)
    #     old_name = item.data()
    #     old_path =  item.path
    #     if old_name == value:
    #         return False
    #     new_root = os.path.dirname(item.path)
    #     new_path = os.path.join(new_root, value).replace('\\', '/')
    #     if not os.path.isdir(old_path):
    #         if os.path.isdir(new_path):
    #             return False
    #     else:
    #         if value in os.listdir(os.path.dirname(old_path)):
    #             return False
    #         try:
    #             os.rename(old_path, new_path)
    #         except:
    #             return False

    #     index = item.parent().childNames.index(old_name)
    #     # item.name = value
    #     self.update_all_sub_item_data(item, old_path, new_path)
    #     item.parent().childNames[index]=value   
    #     if item.isAsset:
    #         item.parent().assets.pop(old_name)
    #         item.parent().assets[value] = item
    #     else:
    #         item.parent().folders.pop(old_name)
    #         item.parent().folders[value] = item
    #     return True
        
    def update_all_sub_item_data(self, item, old_path, new_path):
        item.path = item.path.replace(old_path, new_path)
        # if item.component_config_file:
            # item.component_config_file = item.component_config_file.replace(old_path, new_path)
        if item.childItems:
            for _item in item.childItems:
                self.update_all_sub_item_data(_item, old_path, new_path)
        
    def updata_data_scan(self):
        for _data in self.rootData:
            child_item_list = self.rootItem.listChildren()
            root = self.rootItem
            _item = TreeItem(_data, root)
            root.addChild(_item)
            # self.items.append(_item)
            if _data.get('children'):
                root = _item
                for __data in _data.get('children'):
                    _item = TreeItem(__data, root)
                    root.addChild(_item)
                    # self.items.append(_item)


    def columnCount(self, parent):
        if parent.isValid():
            return parent.internalPointer().columnCount()
        else:
            return self.rootItem.columnCount()
            
    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None
        item = index.internalPointer()
        if role == QtCore.Qt.DisplayRole:
            return item.name
        elif role == QtCore.Qt.DecorationRole:
            if item.childCount():
                if self.view and self.view.isExpanded(index):
                    icon = QtGui.QIcon()
                    icon.addFile(':/icons/folder_open.png', mode=QtGui.QIcon.Normal)
                    icon.addFile(':/icons/folder_open.png', mode=QtGui.QIcon.Disabled)
                    # return QtGui.QIcon(':/icons/folder_open.png')
                    return icon
                # icon = QtGui.QIcon()
                # icon.addPixmap(QtGui.QPixmap(':/icons/folder_win10.png'), QtGui.QIcon.Selected)
                # icon.addPixmap(QtGui.QPixmap(':/icons/folder_close.png'), QtGui.QIcon.Normal)
                # return icon
                icon = QtGui.QIcon()
                icon.addFile(':/icons/folder_close.png', mode=QtGui.QIcon.Normal)
                icon.addFile(':/icons/folder_close.png', mode=QtGui.QIcon.Disabled)
                # return QtGui.QIcon(':/icons/folder_close.png')
                return icon
            if item.isAsset:
                return QtGui.QIcon(':/icons/icon_Asset_dark.png')
            else:
                icon = QtGui.QIcon()
                icon.addFile(':/icons/folder_close.png', mode=QtGui.QIcon.Normal)
                icon.addFile(':/icons/folder_close.png', mode=QtGui.QIcon.Disabled)
                # return QtGui.QIcon(':/icons/folder_close.png')
                return icon

            

        elif role == QtCore.Qt.ToolTipRole:
            return 'help'
        else:
            return None
    def itemFromIndex(self, index):
        if not index.isValid():
            return None
        return index.internalPointer()
    """
    def flags(self, index):
        if not index.isValid():
            return 0
        return super(TreeModel, self).flags(index)
    
    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role==QtCore.Qt.DisplayRole:
            return self.rootItem.data(section)
        return None
    """
    # def flags(self, index):
        # if not index.isValid():
            # return QtCore.Qt.NoItemFlags
        # return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
        # return super(TreeModel, self).flags(index) 
    def index(self, row, column, parent=None):
        #if not hasIndex(row, column, parent):
        #    return QtCore.QModelIndex()
        if not parent:
            parentItem = self.rootItem
        else:
            if not parent.isValid():
                parentItem = self.rootItem
            else:
                parentItem = parent.internalPointer()
        # print '-'*100
        # print parentItem.data()
        # print parentItem.childNames
        # print row
        childItem = parentItem.child(row)
        if childItem:
            childItem.model_index = self.createIndex(row, column, childItem)
            return childItem.model_index
        else:
            
            parentItem.model_index = QtCore.QModelIndex()
            return parentItem.model_index
            
    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()
        childItem = index.internalPointer()
        parentItem = childItem.parent()
        
        # if not parentItem or parentItem == self.rootItem:
            # return QtCore.QModelIndex()
            
        if parentItem == self.rootItem:
            return QtCore.QModelIndex()
        _index = self.createIndex(parentItem.row(), 0, parentItem)
        return _index
        
    def rowCount(self, parent=None):
        if not parent:
            parentItem = self.rootItem
        else:
            if parent.column() > 0:
                return 0
            if not parent.isValid():
                parentItem = self.rootItem
            else:
                parentItem = parent.internalPointer()
        return parentItem.childCount()
    
    def myadd(self):
        return
        childItem = TreeItem([1,2,3], self.rootItem, self.view )
        
        self.rootItem.addChild(childItem)
        self.createIndex(2, 1, childItem)
        
    def insertItem(self, path, parent_item=None, is_asset=False):
        if not parent_item:
            return
        path = path.replace('\\', '/')
        if not parent_item.parent_item:
            index = QtCore.QModelIndex()
        else:
            index = self.createIndex(parent_item.row(), 0, parent_item)
        if is_asset:
            asset_root = os.path.dirname(path).replace('\\', '/')
            name = os.path.basename(asset_root)
            _item = TreeItem(name, asset_root, self.view, parent_item)
            _item.component_config_file = path
            _item.isAsset = True
            # parent_item.assets.append(asset_root)
            parent_item.assets[name]=_item
            self.items.append(_item)
        else:
            name = os.path.basename(path)
            _item = TreeItem(name, path, self.view, parent_item)
            # parent_item.folders.append(path)
            parent_item.folders[name]=_item
            self.items.append(_item)
            
        self.beginInsertRows(index, 0, 0)
        parent_item.addChild(_item)
        self.endInsertRows()
        #self.emit("layoutChanged()")
    # def insertRow(self, row, index):
        
    def removeItem(self):
        return

        #index = self.createIndex(0,0,item)#item.model_index#self.createIndex(0,0,item)
        #index = self.rootItem.model_index
        item = self.rootItem.child(-1)
        
        self.beginRemoveRows(QtCore.QModelIndex(), item.row(), item.row())#item.childCount()-1)
        
        self.rootItem.childItems.pop()
        self.endRemoveRows()
            #self.emit("layoutChanged()")
            
    def insertRows(self,index,  position, rows):
        return
        self.beginInsertRows(index, position, position+rows-1)

        self.endInsertRows()
        return True
